package com.ikaros.controller;

import com.ikaros.VO.LoginVO;
import com.ikaros.controller.admin.AbstractController;
import com.ikaros.model.entity.SysMenu;
import com.ikaros.service.admin.SysMenuService;
import com.ikaros.utils.EhcacheUtil;
import com.ikaros.utils.ResltUtil;
import com.ikaros.utils.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * Created by Ikaros on 2017/9/22.
 */
@RestController
@Slf4j
public class WebController extends AbstractController{
    @Autowired
    private SysMenuService sysMenuService;
    @RequestMapping(value = "/",method = RequestMethod.GET)
    public ModelAndView login() {
        return new ModelAndView("login");
    }

    @RequestMapping(value = "menuList",method = RequestMethod.GET)
    public ResltUtil<SysMenu> menuList(){
        // 用户菜单列表 getAdminId()
        List<SysMenu> menuList = sysMenuService.getUserMenuList(getAdminId());
        return  ResltUtil.success(menuList);
    }

    @RequestMapping("websocket")
    public ModelAndView websocket(){
        return new ModelAndView("admin/websocket");
    }


    @RequestMapping("index")
    public ModelAndView index(Model model){
        model.addAttribute("admin", getAdmin());
        /*model.addAttribute("menuList", menuList);*/
        return new ModelAndView("admin/index");
    }

    /**
     * 登陆
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "login", method = RequestMethod.POST,produces={"application/json;charset=UTF-8"})
    public ResltUtil login(@RequestBody LoginVO user, HttpServletRequest request) throws IOException {
        String username=user.getUsername();
        String password=user.getPassword();
        if (StringUtils.isBlank(username)) {
            return ResltUtil.error("用户名不能为空");
        }
        if (StringUtils.isBlank(password)) {
            return ResltUtil.error("密码不能为空");
        }
        try {
            /*Shiro的subject实质上是当前执行用户的特定视图。
            通过org.apache.shiro.SecurityUtils可以查询当前执行用户：*/
            Subject subject = SecurityUtils.getSubject();
            // sha256加密
            password = new Sha256Hash(password).toHex();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
        } catch (UnknownAccountException e) {
            return ResltUtil.error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return ResltUtil.error(e.getMessage());
        } catch (LockedAccountException e) {
            return ResltUtil.error(e.getMessage());
        } catch (AuthenticationException e) {
            return ResltUtil.error("账户验证失败");
        }
        log.info("success");
        return ResltUtil.success();
    }
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public ModelAndView logout() throws Exception {
        if (ShiroUtil.isLogin()) {
            String cacheName = EhcacheUtil.menuCacheName + getAdminId();
            ehcacheUtil.remove(EhcacheUtil.ADMINMENUEHCACHENAME, cacheName);
            log.info("管理员退出，清空用户菜单列表Cache");
            /*Long userId = ShiroUtil.getUserId();
            if (userId != null && userId.equals(Long.valueOf(constant.adminId))) { // 系统管理员(退出系统备份数据库)
            }*/
            SecurityUtils.getSubject().logout();
        }
        return new ModelAndView("login");
    }
}
